package cn.easyshipping.cloud.config.support;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class RYDApolloConfig implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(RYDApolloConfig.class);

    private static Config config = ConfigService.getAppConfig();

    private ApplicationContext applicationContext;

    public static void initConfig(String namespace) {
        config = ConfigService.getConfig(namespace);
    }

    public static String getProperty(String someKey, String someDefaultValue) {
        return config.getProperty(someKey, someDefaultValue);
    }

    public static void addChangeConfigListener(ConfigChangeListener listener) {
        config.addChangeListener(listener);
    }

    public static boolean removeChangeConfigListener(ConfigChangeListener listener) {
        return config.removeChangeListener(listener);
    }

    @ApolloConfigChangeListener(interestedKeyPrefixes = {"consumer", "common"})
    public void onChange(ConfigChangeEvent changeEvent) {
        refreshZuulProperties(changeEvent);
    }

    private void refreshZuulProperties(ConfigChangeEvent changeEvent) {
        logger.info("Refreshing properties!");

        /**
         * rebind configuration beans, e.g.
         * @see org.springframework.cloud.context.properties.ConfigurationPropertiesRebinder#onApplicationEvent
         */
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));

        logger.info("properties refreshed!");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
